<template>
  <el-drawer
      :title="title"
      v-model="visible"
      size="60%"
      direction="rtl"
      :with-header="true"
  >
    <el-card class="box-shadow">
      <el-descriptions class="margin-top" title="工作内容" :column="3" border>
        <el-descriptions-item label="工单类型">{{ form.type }}</el-descriptions-item>
        <el-descriptions-item label="产品名称">{{ form.productName }}</el-descriptions-item>
        <el-descriptions-item label="产品编码">{{ form.productCode }}</el-descriptions-item>
        <el-descriptions-item label="派单人员">{{ form.sendUserId_dictText }}</el-descriptions-item>
        <el-descriptions-item label="派单时间">{{ form.createTime }}</el-descriptions-item>
        <el-descriptions-item label="优先级">
          <dict-tag :type="DICT_TYPE.BUSINESS_PRIORITY" :value="form.priority||''"/>
        </el-descriptions-item>
        <el-descriptions-item label="需求图片">

          <image-preview :src="form.demandImg" multiple/>
        </el-descriptions-item>
        <el-descriptions-item label="需求附件">
          <upload-file
              v-model="form.demandFile"
              :disabled="true"
              :isShowTip="false"
          />
        </el-descriptions-item>
        <el-descriptions-item label="产品描述">
          <div v-html="form.demandDesc" class="product-desc-content"></div>
        </el-descriptions-item>
      </el-descriptions>
      <div v-if="formType === 'audit'">
        <el-descriptions-item label="完成结果">
          {{ form.finishResult }}
        </el-descriptions-item>

        <el-descriptions-item label="交付路径">
          {{ form.finishPath }}
        </el-descriptions-item>

        <el-descriptions-item label="完成图片">
          <image-preview :src="form.finishImg" multiple/>
        </el-descriptions-item>


        <el-descriptions-item label="完成附件">
          <upload-file
              v-model="form.finishFile"
              :disabled="true"
              :isShowTip="false"
          />
        </el-descriptions-item>
      </div>

      <el-divider/>

      <el-card class="box-shadow">
        <template v-slot:header>
          <div class="clearfix">
            <span>明细数据</span>
            <span style="float: right; padding: 3px 0">工单总分值：{{ score }}</span>
          </div>
        </template>
        <el-table :data="detailsList" style="width: 100%" size="mini">
          <el-table-column prop="name" label="内容" min-width="25%"/>
          <el-table-column prop="columnDesc" label="描述" min-width="30%"/>
          <el-table-column prop="score" label="对应分值" min-width="10%">
            <template #default="scope">  <!-- Vue3 插槽用 #default 替代 slot-scope -->
              {{ scope.row.score + '分' }}
            </template>
          </el-table-column>
          <el-table-column prop="demandNum" label="需求数量" min-width="15%">
            <template #default="scope">
              <el-input-number
                  :min="0"
                  v-model="scope.row.demandNum"
                  placeholder="请输入数量"
                  disabled
                  size="mini"
              />
            </template>
          </el-table-column>
          <el-table-column prop="finishNum" label="实际完成数量" min-width="15%">
            <template #default="scope">
              <el-input-number
                  :min="0"
                  v-model="scope.row.finishNum"
                  placeholder="请输入数量"
                  size="mini"
                  :controls="false"
                  :step="1"
                  @change="(val) => handleNumChange(val, scope.$index)"
                  :disabled="formType === 'audit'"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <el-card class="box-shadow">
        <el-divider/>
        <!-- 表单引用用 formRef 替代原 $refs.form -->
        <el-form ref="formRef" :model="form" :rules="rules" size="mini">
          <div v-if="formType === 'submit'">
            <el-form-item label="完成结果" prop="finishResult">
              <el-input type="textarea" v-model="form.finishResult" style="width: 100%"/>
            </el-form-item>


            <el-form-item label="交付路径" prop="finishPath">
              <el-input type="textarea" v-model="form.finishPath" style="width: 100%"/>
            </el-form-item>

            <el-form-item label="完成图片" prop="finishImg">

              <upload-imgs v-model="form.finishImg"/>

            </el-form-item>
            <el-form-item label="完成文件" prop="finishFile">
              <upload-file v-model="form.finishFile"/>
            </el-form-item>
          </div>
          <div v-else>
            <el-form-item label="审核结果" prop="auditResult">
              <el-radio-group v-model="form.auditResult" size="small">
                <el-radio label="agree" border>同意</el-radio>
                <!--              <el-radio label="reject" border>拒绝</el-radio>-->
              </el-radio-group>
            </el-form-item>

            <el-form-item label="审核备注" :prop="form.auditResult!='reject'?'':'auditRemark'">
              <el-input type="textarea" v-model="form.auditRemark"/>
            </el-form-item>
          </div>
        </el-form>

      </el-card>
    </el-card>

    <div class="drawer-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </div>
  </el-drawer>
</template>

<script setup>
// 1. 引入依赖（Vue3 API、组件、接口）
import {computed, reactive, ref} from 'vue';
import {ElForm} from 'element-plus';
import {DICT_TYPE} from "@/utils/dict";
import {VisualOrderApi} from "@/api/business/design/visual"; // 字典标签组件（原组件依赖）
const message = useMessage()
// 3. 初始化响应式数据（替代 Vue2 data）
const visible = ref(false); // 抽屉显示状态
const formRef = ref(null);  // 表单引用（替代原 this.$refs.form）
const title = ref('');
const formType = ref('')
// 表单数据（用 reactive 处理复杂对象）
const form = ref({
  type: '',
  createTime: '',
  productCode: '',
  productName: '',
  sendUserId_dictText: '',
  priority: '',
  demandImg: '',
  demandFile: '',
  demandDesc: '',
  score: 0,
  details: '[]',
  finishResult: '',
  finishImg: '',
  finishFile: '',
  finishPath:''
});
// 明细列表（用 ref 处理数组）
const detailsList = ref([]);
// 表单验证规则（用 reactive 处理）
const rules = reactive({
  finishResult: [
    {required: true, message: '请填写完成结果', trigger: 'blur'}
  ],
  auditResult: [
    {required: true, message: '请选择审核结果', trigger: 'blur'}
  ],
  auditRemark: [
    {required: true, message: '请填写拒绝理由', trigger: 'blur'}
  ]
});


const score = computed(() => {
  let total = 0;
  detailsList.value.forEach(item => {
    const itemScore = Number(item.score) || 0;
    const itemFinishNum = Number(item.finishNum) || 0;
    // 分步计算并修正每一步的精度
    total += Math.round(itemScore * itemFinishNum * 100) / 100;
  });
  // 对最终结果再做一次精度修正，确保只保留两位小数
  return Math.round(total * 100) / 100;
});


const showVisible = (type, row) => {
  formType.value = type
  if (formType.value === 'submit') {
    title.value = '完成工单'
  } else if (formType.value === 'audit') {
    title.value = '审核工单'
  } else {
    message.error('类型错误,请联系管理员')
    return;
  }
  form.value = row
  visible.value = true;
  detailsList.value = form.value.details ? JSON.parse(form.value.details) : [];
  // 初始化实际完成数量（默认等于需求数量）
  detailsList.value.forEach((item, index) => {
    detailsList.value[index].finishNum = Number(item.demandNum) ?? 0;
  });
};

// 提交表单
const submitForm = async () => {
  // 表单验证（Vue3 支持 async/await 形式）
  await formRef.value.validate();
  // 赋值总分和明细数据
  form.value.score = score.value;
  form.value.details = JSON.stringify(detailsList.value);

  if (Array.isArray(form.value.finishImg)) {
    form.value.finishImg = form.value.finishImg.join(',')
  }
  // 处理需求附件（数组转字符串）
  if (Array.isArray(form.value.finishFile)) {
    form.value.finishFile = form.value.finishFile.join(',')
  }

  if (formType.value === 'submit') {
    await VisualOrderApi.submitVisualInfo(form.value);
  } else if (formType.value === 'audit') {
    await VisualOrderApi.auditVisualInfo(form.value);
  } else {
    message.error('系统错误，请联系管理员！');
  }
  // 调用提交接口

  visible.value = false;
  emit('success');

};

// 处理完成数量变更（向下取整）
const handleNumChange = (value, index) => {
  // 确保值为数字且向下取整
  detailsList.value[index].finishNum = Math.floor(Number(value)) || 0;
};

// 8. 定义组件事件（向父组件传值，替代原 this.$emit）
const emit = defineEmits(['success']);
// 暴露组件方法（供父组件调用）
defineExpose({showVisible});

</script>

<style scoped>
/* 保留原样式，补充必要布局样式 */
.box-shadow {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
  margin-bottom: 16px;
}

.margin-top {
  margin-top: 16px;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 16px;
  gap: 8px;
  border-top: 1px solid #eee;
  margin-top: 16px;
}

.product-desc-content {
  white-space: pre-wrap; /* 处理换行符，避免内容挤在一起 */
  word-break: break-all; /* 长文本自动换行 */
  line-height: 1.5;
}
</style>
